<template>
    <div>
        <div class="search-form">
            <el-form :model="searchForm" :rules="rules" inline>
                <el-form-item label="学生ID">
                    <el-input v-model="searchForm.studentId" @keyup.enter="search" placeholder="请输入学生ID"></el-input>
                </el-form-item>
                <el-form-item label="学生姓名">
                    <el-input v-model="searchForm.studentName" @keyup.enter="search" placeholder="请输入学生姓名"></el-input>
                </el-form-item>
                <el-form-item style="margin-bottom: 40px">
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="inputDiv">
            <el-form-item label="姓名">
                <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="账号">
                <el-input v-model="addForm.studentID" />
            </el-form-item>
          <div style="display: flex;flex-direction: row">
            <span style="flex: 0.865;margin-top: 8px">默认密码：123456</span>
            <div>
              <el-button style="margin-top: 0px" class="import-el-button" @click="addPerson()">添加</el-button>
            </div>
          </div>
        </div>
        <el-button class="import-el-button" @click="downLoadStu()">下载名单</el-button>
        <el-table ref="multipleTableRef" :data="displayedPeople" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column property="name" label="学生姓名" />
            <el-table-column property="studentID" label="学生ID" show-overflow-tooltip />
            <el-table-column label="操作" width="360">
                <template #default="{ row }">
                    <el-button link type="primary" size="small" @click="deleteSingleStudentFun(row)"
                             style="margin-top: 0px;"><router-link :to="'/studentDetails/' + row.studentID" style="color: #409eff" @click="findDetail(row)"><p style="font-size: 14px">查看详情</p></router-link></el-button>
                    <el-button v-if="matchUrlData === 'stu'" link type="primary" size="small" @click="editPerson(row)"
                        style="margin-top: 0px;font-size: 14px">编辑</el-button>
                    <el-dialog title="编辑学生信息" v-model="dialogFormVisible" :before-close="handleClose">
                        <el-form :model="form">
                            <el-form-item label="学生姓名" :label-width="formLabelWidth">
                                <el-input v-model="form.name" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="学生ID" :label-width="formLabelWidth">
                                <el-input v-model="form.studentID" autocomplete="off" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer" @click="dialogFormVisible = false">
                                <el-button>取消</el-button>
                                <el-button type="primary" @click="saveEdit(row)">
                                    確定
                                </el-button>
                            </span>
                        </template>
                    </el-dialog>
                    <el-button link type="primary" size="small" @click="deleteSingleStudentFun(row)"
                        style="margin-top: 0px;font-size: 14px">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[5, 10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="people.length">
        </el-pagination>
        <div style="margin-top: 20px">
            <el-button @click="deleteBatchTeacher">批量删除</el-button>
        </div>
    </div>
</template>
  
<script setup>
import { ref, toRefs, reactive, computed, watch, onMounted } from 'vue';
import { ElNotification, ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElPagination, ElMessage } from 'element-plus';
import XLSX from 'xlsx';
import { useStore } from '../store'
import { ElTable, ElUpload } from 'element-plus'
import { addSingleStudent, deleteSingleStudent, editorStudentInfo, deleteBatchStudents, selectSudentInfoService, allCourseStudentAttend, deleteSingleStudentInClass, deleteBatchStudentsInClass } from '@/api/adminApi/allAdmin'
import { useRoute } from 'vue-router';
const router = useRoute();
const searchForm = ref({
    studentId: '',
    studentName: ''
});
const store = useStore()
const fileList = ref()
watch(
    () => store.studentList,
    () => people.value = store.studentList,
    { deep: true }
)
const props = defineProps({
    tableData: Array
})
const resetForm = () => {
    searchForm.value.studentId = '';
    searchForm.value.studentName = '';
};
const people = ref(props.tableData ?? store.studentList);
const matchUrlData = ref(props.tableData ? 'class' : 'stu')//true为学生表数据
// const matchUrl = () => {
//     if (props.tableData) {
//         matchUrlData.value = 'class'
//     }
// }
// const people=ref(props.tableData)
const displayedPeople = ref([]); // 当前显示的数据
const currentPage = ref(1);
const pageSize = ref(10);

const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    displayedPeople.value = paginateData();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    displayedPeople.value = paginateData();
};

const paginateData = () => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    return people.value.slice(startIndex, endIndex);
};
onMounted(() => {
    displayedPeople.value = paginateData();
})
const form = ref({
    studentID: '',
    name: '',
    editIndex: 0
});
const addForm = ref({
    name: '',
    studentID: ''
});
const multipleTableRef = ref()
const dialogFormVisible = ref(false);
const addPerson = async () => {
    if (matchUrlData.value === 'stu') {
        const data = {
            name: addForm.value.name,
            studentID: addForm.value.studentID,
            password: '123456',
            classID: store.detailClass.classID
        };
        displayedPeople.value.push(data)
        addForm.value = {}
        await addSingleStudent(data)
    }
    else {
        const data = {
            name: addForm.value.name,
            studentID: addForm.value.studentID,
            password: '123456',
            classID: store.detailClass.classID
        };
        displayedPeople.value.push(data)
        addForm.value = {}
        await addSingleStudent(data)
    }
    // ElMessage.success('')

};
//保存多选行的信息
const selectionRow = ref([])
const handleSelectionChange = (section) => {
    selectionRow.value = section
    console.log(selectionRow.value, 'selectionRow')
}
//批量删除
const deleteBatchTeacher = async () => {
    console.log('matchUrlData', matchUrlData)
    if (matchUrlData.value === 'stu') {
        const data = []
        selectionRow.value.map((item, index) => {
            data.push(item.studentID)
            people.value.map((list, idx) => {
                if (item.studentID === list.studentID)
                    displayedPeople.value.splice(idx, 1)
            })
        })
        await deleteBatchStudents(data)
    } else {
        const data = []
        selectionRow.value.map((item, index) => {
            data.push(item.studentID)
            // data.push()
            people.value.map((list, idx) => {
                if (item.studentID === list.studentID)
                    displayedPeople.value.splice(idx, 1)
            })
        })
        await deleteBatchStudentsInClass()
    }
}
const editPerson = async (row) => {
    // 处理选中行数据
    form.value.name = row.name;
    form.value.studentID = row.studentID;
    dialogFormVisible.value = true;
}
//删除单个學生
const deleteSingleStudentFun = async (row) => {
    if (matchUrlData.value == 'stu') {
        const index = displayedPeople.value.findIndex(item => item.studentID === row.studentID);
        displayedPeople.value.splice(index, 1)
        await deleteSingleStudent(row.studentID)

    } else {
        console.log('matchUrlData', matchUrlData, '123')
        const index = displayedPeople.value.findIndex(item => item.studentID === row.studentID);
        displayedPeople.value.splice(index, 1)
        const data = {
            classID: store.detailClass.classID,
            studentID: row.studentID
        }
        await deleteSingleStudentInClass(data)
    }
};
//保存编辑内容
const saveEdit = async () => {
    const data = {
        name: form.value.name,
        password: "123456",//设为初始值
        studentID: form.value.studentID
    }
    await editorStudentInfo(data)
    const index = people.value.findIndex((item) => item.studentID === form.value.studentID)
    people.value[index].name = form.value.name
}
const search = async () => {
    let result={
        studentID:searchForm.value.studentId,
        name:searchForm.value.studentName,
        pageSize:20,
        pageNum:1
    }
    const res = await selectSudentInfoService(result)
    displayedPeople.value = res.data
    people.value=res.data

};

//查看详情
const findDetail = async (data) => {
    store.setDetailStudent(data)
    //加入的课程
    await allCourseStudentAttend(data.studentID)
        .then((res) => store.setAttendClassOfStu(res.data))
        .catch((err) => {
            store.setAttendClassOfStu([])
            alert('該學生還未加入任何課堂')
        })
    // const list=await allCourseStudentAttend(data)
    // if(list.code!==200){
    //     store.setAttendClassOfStu([])
    // }
    // else{
    //     store.setAttendClassOfStu(list.data)
    // }
}

const handleCloseDialog = (done) => {
    form.value.studentID = '';
    form.value.teacherName = '';
    done();
};

// 将响应式数据转换为可解构的对象
const { value: reactivePeople } = toRefs(people);
const downLoadStu = () => {
    const worksheet = XLSX.utils.json_to_sheet(people.value);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, 'students.xlsx');
}
const handleFileUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 将数据存入ref
        people.value = jsonData.map((row, index) => {
            if (index === 0) return null; // 跳过表头行
            const [id, studentID, studentName] = row;
            return { id, studentID, studentName };
        }).filter(Boolean);
    };

    reader.readAsArrayBuffer(file);
}

</script>
  
<style>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.import_div {
    display: inline-block;
    margin-left: 28%;
}
.search-form {
  margin-bottom: 20px;

}
</style>
<!-- <template>
    <div>
        <div class="search-form">
            <el-form :model="searchForm" :rules="rules" inline>
                <el-form-item label="学生ID">
                    <el-input v-model="searchForm.studentId" @keyup.enter="search" placeholder="请输入学生ID"></el-input>
                </el-form-item>
                <el-form-item label="学生姓名">
                    <el-input v-model="searchForm.studentName" @keyup.enter="search" placeholder="请输入学生姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="inputDiv">
            <el-form-item label="姓名">
                <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="账号">
                <el-input v-model="addForm.studentID" />
            </el-form-item>
            默认密码：123456
            <el-button class="import-el-button" @click="addPerson()">添加</el-button>
        </div>
        <el-button class="import-el-button" @click="downLoadStu()">下载名单</el-button>
        <el-table ref="multipleTableRef" :data="displayedPeople" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column property="name" label="学生姓名" />
            <el-table-column property="studentID" label="学生ID" show-overflow-tooltip />
            <el-table-column label="操作" width="360">
                <template #default="{ row }">
                    <router-link :to="'/studentDetails/' + row.studentID" @click="findDetail(row)">查看详情</router-link>
                    <el-button v-if="matchUrlData === 'stu'" link type="primary" size="small" @click="editPerson(row)"
                        style="margin-top: 0px;">编辑</el-button>
                    <el-dialog title="编辑学生信息" v-model="dialogFormVisible" :before-close="handleClose">
                        <el-form :model="form">
                            <el-form-item label="学生姓名" :label-width="formLabelWidth">
                                <el-input v-model="form.name" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="学生ID" :label-width="formLabelWidth">
                                <el-input v-model="form.studentID" autocomplete="off" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer" @click="dialogFormVisible = false">
                                <el-button>取消</el-button>
                                <el-button type="primary" @click="saveEdit(row)">
                                    確定
                                </el-button>
                            </span>
                        </template>
                    </el-dialog>
                    <el-button link type="primary" size="small" @click="deleteSingleStudentFun(row)"
                        style="margin-top: 0px;">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[5, 10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="people.length">
        </el-pagination>
        <div style="margin-top: 20px">
            <el-button @click="deleteBatchTeacher">批量删除</el-button>
        </div>
    </div>
</template> -->
  
<!-- <script setup>
import { ref, toRefs, reactive, computed, watch, onMounted } from 'vue';
import { ElNotification, ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElPagination, ElMessage } from 'element-plus';
import XLSX from 'xlsx';
import { useStore } from '../store'
import { ElTable, ElUpload } from 'element-plus'
import { addSingleStudent, deleteSingleStudent, editorStudentInfo, deleteBatchStudents, selectSudentInfoService, allCourseStudentAttend, deleteSingleStudentInClass, deleteBatchStudentsInClass } from '@/api/adminApi/allAdmin'
import { useRoute } from 'vue-router';
const router = useRoute();
const searchForm = ref({
    studentId: '',
    studentName: ''
});
const store = useStore()
const fileList = ref()
watch(
    () => store.studentList,
    () => people.value = store.studentList,
    { deep: true }
)
const props = defineProps({
    tableData: Array
})
const resetForm = () => {
    searchForm.value.studentId = '';
    searchForm.value.studentName = '';
};
const people = ref(props.tableData ?? store.studentList);
const matchUrlData = ref(props.tableData ? 'class' : 'stu')//true为学生表数据
// const matchUrl = () => {
//     if (props.tableData) {
//         matchUrlData.value = 'class'
//     }
// }
// const people=ref(props.tableData)
const displayedPeople = ref([]); // 当前显示的数据
const currentPage = ref(1);
const pageSize = ref(10);

const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    displayedPeople.value = paginateData();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    displayedPeople.value = paginateData();
};

const paginateData = () => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    return people.value.slice(startIndex, endIndex);
};
onMounted(() => {
    displayedPeople.value = paginateData();
})
const form = ref({
    studentID: '',
    name: '',
    editIndex: 0
});
const addForm = ref({
    name: '',
    studentID: ''
});
const multipleTableRef = ref()
const dialogFormVisible = ref(false);
const addPerson = async () => {
    if (matchUrlData.value === 'stu') {
        const data = {
            name: addForm.value.name,
            studentID: addForm.value.studentID,
            password: '123456',
            classID: store.detailClass.classID
        };
        displayedPeople.value.push(data)
        addForm.value = {}
        await addSingleStudent(data)
    }
    else {
        const data = {
            name: addForm.value.name,
            studentID: addForm.value.studentID,
            password: '123456',
            classID: store.detailClass.classID
        };
        displayedPeople.value.push(data)
        addForm.value = {}
        await addSingleStudent(data)
    }
    // ElMessage.success('')

};
//保存多选行的信息
const selectionRow = ref([])
const handleSelectionChange = (section) => {
    selectionRow.value = section
    console.log(selectionRow.value, 'selectionRow')
}
//批量删除
const deleteBatchTeacher = async () => {
    console.log('matchUrlData', matchUrlData)
    if (matchUrlData.value === 'stu') {
        const data = []
        selectionRow.value.map((item, index) => {
            data.push(item.studentID)
            people.value.map((list, idx) => {
                if (item.studentID === list.studentID)
                    displayedPeople.value.splice(idx, 1)
            })
        })
        await deleteBatchStudents(data)
    } else {
        const data = []
        selectionRow.value.map((item, index) => {
            data.push(item.studentID)
            // data.push()
            people.value.map((list, idx) => {
                if (item.studentID === list.studentID)
                    displayedPeople.value.splice(idx, 1)
            })
        })
        await deleteBatchStudentsInClass()
    }
}
const editPerson = async (row) => {
    // 处理选中行数据
    form.value.name = row.name;
    form.value.studentID = row.studentID;
    dialogFormVisible.value = true;
}
//删除单个學生
const deleteSingleStudentFun = async (row) => {
    if (matchUrlData.value == 'stu') {
        const index = displayedPeople.value.findIndex(item => item.studentID === row.studentID);
        displayedPeople.value.splice(index, 1)
        await deleteSingleStudent(row.studentID)

    } else {
        console.log('matchUrlData', matchUrlData, '123')
        const index = displayedPeople.value.findIndex(item => item.studentID === row.studentID);
        displayedPeople.value.splice(index, 1)
        const data = {
            classID: store.detailClass.classID,
            studentID: row.studentID
        }
        await deleteSingleStudentInClass(data)
    }
};
//保存编辑内容
const saveEdit = async () => {
    const data = {
        name: form.value.name,
        password: "123456",//设为初始值
        studentID: form.value.studentID
    }
    await editorStudentInfo(data)
    const index = people.value.findIndex((item) => item.studentID === form.value.studentID)
    people.value[index].name = form.value.name
}
const search = async () => {
    let result={
        studentID:searchForm.value.studentId,
        name:searchForm.value.studentName,
        pageSize:20,
        pageNum:1
    }
    const res = await selectSudentInfoService(result)
    displayedPeople.value = res.data
    people.value=res.data

};

//查看详情
const findDetail = async (data) => {
    store.setDetailStudent(data)
    //加入的课程
    await allCourseStudentAttend(data.studentID)
        .then((res) => store.setAttendClassOfStu(res.data))
        .catch((err) => {
            store.setAttendClassOfStu([])
            alert('該學生還未加入任何課堂')
        })
    // const list=await allCourseStudentAttend(data)
    // if(list.code!==200){
    //     store.setAttendClassOfStu([])
    // }
    // else{
    //     store.setAttendClassOfStu(list.data)
    // }
}

const handleCloseDialog = (done) => {
    form.value.studentID = '';
    form.value.teacherName = '';
    done();
};

// 将响应式数据转换为可解构的对象
const { value: reactivePeople } = toRefs(people);
const downLoadStu = () => {
    const worksheet = XLSX.utils.json_to_sheet(people.value);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, 'students.xlsx');
}
const handleFileUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 将数据存入ref
        people.value = jsonData.map((row, index) => {
            if (index === 0) return null; // 跳过表头行
            const [id, studentID, studentName] = row;
            return { id, studentID, studentName };
        }).filter(Boolean);
    };

    reader.readAsArrayBuffer(file);
}

</script> -->
  
<!-- <style>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.import_div {
    display: inline-block;
    margin-left: 28%;
}
.search-form {
  margin-bottom: 20px;

}
</style> -->